package com.zyy.joseata.socket;

import com.alibaba.fastjson.JSONObject;
import com.zyy.joseata.bo.SocketBO;
import com.zyy.joseata.bo.TxClazzBO;
import com.zyy.joseata.constant.TxEventTypeConst;
import com.zyy.joseata.util.JoSpringBeanUtil;
import com.zyy.joseata.util.ThreadLocalUtil;
import com.zyy.joseata.util.TxClazzMapUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class SocketReadHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws InvocationTargetException, IllegalAccessException {
        ByteBuf byteBuf = (ByteBuf) msg;
        String receiveData = byteBuf.toString(StandardCharsets.UTF_8);
        log.info("服务器返回的数据: {}",receiveData);

        SocketBO socketData = JSONObject.parseObject(receiveData,SocketBO.class);
        TxClazzBO txClazz;
        Object bean;
        switch (socketData.getEventType()){
            case TxEventTypeConst.GLOBAL_TX_RESPONSE_CONFIRM:
                ThreadLocalUtil.setTxId(socketData.getTxId());
                txClazz = TxClazzMapUtil.getTxClazz(socketData.getTxId());
                bean = JoSpringBeanUtil.getBean(txClazz.getClazz());
                if(txClazz.getConfirmMethod() != null){
                    txClazz.getConfirmMethod().invoke(bean);
                }
                break;
            case TxEventTypeConst.GLOBAL_TX_RESPONSE_CANCEL:
                ThreadLocalUtil.setTxId(socketData.getTxId());
                txClazz = TxClazzMapUtil.getTxClazz(socketData.getTxId());
                bean = JoSpringBeanUtil.getBean(txClazz.getClazz());
                if(txClazz.getCancelMethod() != null){
                    txClazz.getCancelMethod().invoke(bean);
                }
                break;
        }

        byteBuf.release();
    }

}
